package controller

import (
	models "fileshare/controller/modles"
	"fileshare/controller/server"
	"fileshare/controller/tools"
	"fileshare/utils"
	"net/http"

	"github.com/gin-gonic/gin"
)

/**
* @program: fileshare
*
* @description:
*
* @author: Koco.Allien
*
* @create: 2020-04-06 11:55
**/
//只展示自己的文件,不展示别人分享的文件
func FileSelfController(c *gin.Context) {
	aid := tools.GatQuery(c, "active", 2)
	utils.MsgToLog("个人文件:FileSelfController")
	data, u, ok := tools.StartDate(c, "个人文件", aid)
	if !ok {
		data["error"] = "操作超出权限"
		c.HTML(http.StatusOK, "index.html", data)
	} else {
		files, count := server.GetSelfFiles(-1, 100, u.ID)
		data["files"] = files
		data["count"] = count
		c.HTML(http.StatusOK, "selffile.html", data)
	}
}

//fid={{$elem.ID}}&&active={{.active}}
//删除个人文件,不删除自己分享的文件
//删除分享的文件,不删除自己的文件  --> 各删各的,只是自己没有,
func FdeleteController(c *gin.Context) {
	fid := tools.GatQuery(c, "fid", 1)
	aid := tools.GatQuery(c, "active", 2)
	utils.MsgToLog("个人文件:FdeleteController")
	data, u, ok := tools.StartDate(c, "个人文件", aid)
	if !ok || fid == 1 {
		data["error"] = "操作超出权限"
		c.HTML(http.StatusOK, "index.html", data)
	} else {
		server.DelFile(fid)
		data["error"] = "删除成功"
		//主页访问删除操作
		if aid == 1 {
			data["files"] = server.GetPublicFiles()
			c.HTML(http.StatusOK, "index.html", data)
			return
		}
		files, count := server.GetSelfFiles(-1, 100, u.ID)
		data["files"] = files
		data["count"] = count
		c.HTML(http.StatusOK, "selffile.html", data)
	}
}

// 重命名 fid={{$elem.ID}}&&active={{.active}}
func FupdateController(c *gin.Context) {
	aid := tools.GatQuery(c, "active", 2)
	utils.MsgToLog("个人文件:FupdateController")
	data, _, ok := tools.StartDate(c, "个人文件", aid)
	if !ok {
		data["error"] = "操作超出权限"
		c.HTML(http.StatusOK, "selffile.html", data)
	} else {
		//文件修改界面
		fid := tools.GatQuery(c, "fid", 1)
		file := server.GetFile(fid)
		data["fid"] = fid
		data["fname"] = file.FFname
		c.HTML(http.StatusOK, "updatefile.html", data)
	}
}

// 重命名文件名称
func FfupdateControllerPost(c *gin.Context) {
	aid := tools.GatQuery(c, "active", 2)
	utils.MsgToLog("个人文件:FfupdateControllerPost")
	data, u, ok := tools.StartDate(c, "个人文件", aid)
	if !ok {
		data["error"] = "操作超出权限"
		c.HTML(http.StatusOK, "index.html", data)
	} else {
		msg := "操作成功"

		fid := tools.GatQuery(c, "fid", 1)
		fname := c.PostForm("fname")
		if len(fname) == 0 {
			msg = "无效名称"
		} else {
			f := &models.BelongInfo{
				ID:     fid,
				FFname: fname,
			}
			err := server.Updatefile(f)
			if err != nil {
				msg = "更新失败"
			}
		}
		files, count := server.GetSelfFiles(-1, 100, u.ID)
		data["files"] = files
		data["count"] = count
		data["error"] = msg
		c.HTML(http.StatusOK, "selffile.html", data)

	}
}
